<template>
  <div class="loginInner">
    <div class="form absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[760px] h-[480px]">
      <div class="descrie mb-10">
        <div class="title my-4 text-3xl leading-none">登录</div>
      </div>
      <el-form ref="formRef" :model="formParams" :rules="rules" size="large" status-icon>
        <el-form-item prop="userName">
          <span>账户</span>
          <el-input
            ref="nameRef"
            v-model="formParams.userName"
            placeholder="请输入账户名"
            clearable
            @keyup.enter="passRef?.focus()"
          >
            <!-- <template #prefix>
              <SvgIcon name="user" :size="18"></SvgIcon>
            </template> -->
          </el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <span>密码</span>
          <el-input
            ref="passRef"
            v-model="formParams.passWord"
            show-passWord
            placeholder="请输入密码"
            clearable
            @keyup.enter="handleSubmit"
          >
            <!-- <template #prefix>
              <SvgIcon name="lock" :size="18"></SvgIcon>
            </template> -->
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="w-full" type="primary" :loading="submitLoading" @click="handleSubmit"> 登录 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { LoginApi } from '@/api/modules/login'
import { ElInput, FormInstance, FormItemRule } from 'element-plus'
import { useRouter } from 'vue-router'
import { HOME_URL } from '@/config/config'
import { Session } from '@/utils/storage'
const store = useUserStore()
interface form {
  userName: string
  passWord: string
}
const router = useRouter()
const formRef = ref<FormInstance>()
const passRef = ref<InstanceType<typeof ElInput>>()
const nameRef = ref<InstanceType<typeof ElInput>>()
const formParams = reactive<form>({
  userName: '',
  passWord: ''
})
type Arrayable<T> = T | T[]

const rules = reactive<Record<string, Arrayable<FormItemRule>>>({
  userName: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
  passWord: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
})

const submitLoading = ref(false)
const handleSubmit = () =>
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      loginFun()
    }
  })
onMounted(() => {
  nameRef.value?.focus()
})
const loginFun = async () => {
  submitLoading.value = true
  let res: any = await LoginApi.Login({ ...formParams })
  if (res.data) {
    submitLoading.value = false
    Session.set('token', res.data.token)
    store.setToken(res.data.token)
    router.push(HOME_URL)
  }
}
</script>
<style scoped lang="scss">
.loginInner {
  width: 100%;
  height: 100%;
  background-color: rgba(127, 255, 212, 0.2);
}
</style>
